﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.IO.Ports;
using TCPSocket_DLL;
using System.Diagnostics;
using WebServer;

namespace Server {
    public partial class Server : Form {

        private TcpSocket mControlTcpSocket;
        private TcpSocket mDataTcpSocket;
        private MyWebServer mMws;
        private readonly ProcessStartInfo mNotepadInfo;
        private Process mNotepad;
        public Server() {
            InitializeComponent();
            Width = 400;
            Height = 470;

            mNotepadInfo = new ProcessStartInfo("notepad.exe") {
                Arguments =
                    string.Format("{0}{1}Http{1}Data{1}vdirs.dat", Application.StartupPath, Path.DirectorySeparatorChar)
            };


        }
        private void InitSerial() {
            string[] list = SerialPort.GetPortNames();
        ReTry:
            if (list.Length > 0) {
                Array.Sort(list);

                portListComboBox.Items.AddRange(list);
                portListComboBox.SelectedIndex = (portListComboBox.SelectedIndex > 0 ? 1 : 0);

                myConn.DataReceived += MyConnDataReceived;
            } else {
                DialogResult dr = MessageBox.Show(@"Your system doesn't have any serial ports!", @"Missing serial port!", MessageBoxButtons.AbortRetryIgnore);
                switch (dr) {
                    case DialogResult.Abort:
                        Close();
                        break;
                    case DialogResult.Retry:
                        goto ReTry;
                }
            }
        }
        private void InitNetworkSockets() {
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ipa in ipHost.AddressList) {
            }
            toolStripStatusLabelLocalIP.Text = string.Format(@"My IP addresses: {0}", ipHost.AddressList[0]);

            mControlTcpSocket = new TcpSocket(8090, DataStreamType.STRING);

            mControlTcpSocket.Connected += Connected;
            mControlTcpSocket.DataReceived += ControlDataRead;
            mControlTcpSocket.Error += ErrorMsg;
            mControlTcpSocket.ConnectedToClient += connToClient;

            mDataTcpSocket = new TcpSocket(9090, DataStreamType.BITMAP);
            mDataTcpSocket.Connected += Connected;
            mDataTcpSocket.ConnectedToClient += connToClient;
            camCapture.NewPic += SendFeed;
        }

        private void ServerLoad(object sender, EventArgs e) {
            InitSerial();
            InitNetworkSockets();
            if (!mControlTcpSocket.IsServerStarted)
                mControlTcpSocket.StartServer();
            if (!mDataTcpSocket.IsServerStarted)
                mDataTcpSocket.StartServer();
        }
        private void Connected(object from, EventArgs e) {
            Invoke(new MethodInvoker(delegate {
                listBox1.Items.Add(from);
                mDataTcpSocket.SetHost = ((string)from).Substring(0, (((string)from).IndexOf(':')));
                mControlTcpSocket.SetHost = ((string)from).Substring(0, (((string)from).IndexOf(':')));
            }));
        }
        private void ErrorMsg(object errorMsg, EventArgs e) {
            Invoke(new MethodInvoker(delegate { MessageBox.Show(((string)errorMsg)); }));
        }
        private void connToClient(object endPoint, EventArgs e) {
            EndPoint ep = endPoint as EndPoint;
            IPEndPoint ipEndPoint = (IPEndPoint)ep;
            if (ipEndPoint != null) MessageBox.Show(ipEndPoint.Address.ToString());
        }

        private void ControlDataRead(object controlData, EventArgs e) {
            //string str = controlString as string;
            Invoke(new MethodInvoker(delegate {
                if (controlData != null) {
                    byte[] str = controlData as byte[];
                    int i;
                    for (i = 0; i < str.Length; i++) {
                        listBox2.Items.Add(Convert.ToByte(str[i]));
                        listBox2.SelectedIndex = -1;
                        if (str[i] == 0) break;
                    }
                    if (myConn.IsOpen)
                        myConn.Write(str, 0, i);
                }
            }));
        }
        private void ResetComPortList() {
            string[] list = SerialPort.GetPortNames();
            Array.Sort(list);
            portListComboBox.Items.Clear();
            portListComboBox.Items.AddRange(list);
            portListComboBox.SelectedIndex = 0;
        }
        // ReSharper disable UnusedMember.Local
        private void StopComPort() {
            // ReSharper restore UnusedMember.Local
            myConn.Write("SS");
            myConn.Close();
        }
        // ReSharper disable UnusedMember.Local
        private void SetSerial() {
            // ReSharper restore UnusedMember.Local
            myConn.BaudRate = 9600;
            myConn.PortName = Text;
            myConn.DataBits = 8;
            myConn.Parity = Parity.None;
            myConn.StopBits = StopBits.One;
            myConn.ReceivedBytesThreshold = 1;

            //myConn.Encoding = Encoding.GetEncoding("ISO-8859-2");
            // myConn.Encoding = Encoding.UTF8;
        }

        private void ButtonConnectComClick(object sender, EventArgs e) {
            if (myConn.IsOpen) {
                myConn.Close();
                ResetComPortList();
                portListComboBox.Enabled = true;
            } else {
                myConn.Open();
                portListComboBox.Enabled = false;
            }
            buttonConnectCom.Text = (myConn.IsOpen ? "Close" : "Open");
        }
        private void ServerFormClosed(object sender, FormClosedEventArgs e) {
            if (mControlTcpSocket != null)
                mControlTcpSocket.Stop();
            if (mDataTcpSocket != null)
                mDataTcpSocket.Stop();
            camCapture.Stop();
            try {
                //Web szerver nem feltételül és akkor null az MWS
                mMws.Stop();
                // ReSharper disable EmptyGeneralCatchClause
            } catch (Exception)
                // ReSharper restore EmptyGeneralCatchClause
            { }
        }

        private void ListBox2KeyPress(object sender, KeyPressEventArgs e) {
            mControlTcpSocket.SendString(e.KeyChar + "");
        }
        private void SendFeed(object bMap, EventArgs e) {
            if (mDataTcpSocket.IsReadyToSend)
                mDataTcpSocket.SendBitmap(bMap);
        }
        private void PanelImageClick(object sender, EventArgs e) {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK) {
                panelImage.BackgroundImage = new Bitmap(ofd.FileName);
                mDataTcpSocket.SendBitmap(panelImage.BackgroundImage);
            }
        }

        private void MyConnDataReceived(object sender, SerialDataReceivedEventArgs e) {
            Invoke(new MethodInvoker(delegate {
                string tmp = myConn.ReadExisting();
                mControlTcpSocket.SendString(tmp);
                listBox3.Items.Add(tmp);
                listBox3.SelectedIndex = -1;
            }));
        }

        private void PortListComboBoxSelectedIndexChanged(object sender, EventArgs e) {
            myConn.PortName = portListComboBox.SelectedItem as string;
        }

        private void ButtonClearLogsClick(object sender, EventArgs e) {
            listBox2.Items.Clear();
            listBox3.Items.Clear();
        }

        private void UpdateMessages(object message, EventArgs e) {
            Invoke(new MethodInvoker(delegate {
                listBoxWebServer.Items.Add(message);
            }));
        }

        private void Label6Click(object sender, EventArgs e) {
            if (mNotepad == null) {
                mNotepad = Process.Start(mNotepadInfo);
            } else
                if (mNotepad.HasExited) {
                    mNotepad.Start();
                }
        }

        private void ToolStripButtonWebClick(object sender, EventArgs e) {
            if (mMws == null || !mMws.IsRuning) {
                mMws = new MyWebServer(Directory.GetCurrentDirectory() + "\\http\\");
                mMws.Messages += UpdateMessages;
                //ellenőrizni van e kép amit lehet küldeni !
                mMws.Start();

            } else {
                mMws.Stop();
                mMws.Messages -= UpdateMessages;
            }
        }

        private void ToolStripButtonQuitClick(object sender, EventArgs e) {
            if (mControlTcpSocket != null)
                mControlTcpSocket.Stop();
            if (mDataTcpSocket != null)
                mDataTcpSocket.Stop();
            camCapture.Stop();
            try {
                //Web szerver nem feltételül és akkor null az MWS
                mMws.Stop();
                // ReSharper disable EmptyGeneralCatchClause
            } catch (Exception)
                // ReSharper restore EmptyGeneralCatchClause
            { }
            
            Close();
        }

        private void ToolStripButtonLogClick(object sender, EventArgs e) {
            if (toolStripButtonLog.Checked) {
                Width = 845;
                Height = 650;
            } else {
                Width = 400;
                Height = 470;
            }
        }
    }
}

